package utils;

import entity.Product;
import entity.User;
import entity.UserRole;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class ServletUtil {

    /**
     * Deze methode is handig om parameters uit bijvoorbeeld de URL te halen.
     *
     * @param request
     * @param name
     * @param defaultValue
     * @return
     */
    public static long getLong(String input, long defaultValue) {
        long result;
        try {
            result = Long.parseLong(input);
        } catch (NumberFormatException ex) {
            result = defaultValue;
        }
        return result;
    }

    public static double getDouble(String input, double defaultValue) {
        double result;
        try {
            result = Double.parseDouble(input);
        } catch (NumberFormatException ex) {
            result = defaultValue;
        }
        return result;
    }

    public static int getInt(String input, int defaultValue) {
        int result;
        try {
            result = Integer.parseInt(input);
        } catch (NumberFormatException ex) {
            result = defaultValue;
        }
        return result;
    }
    
    public static Map<String, FileItem> parseMultipartRequest(HttpServletRequest request) {
        
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        Map<String, FileItem> formFields = new HashMap<String, FileItem>();
        
        try {
            if(request.getMethod().equals("POST")) {

                List items = upload.parseRequest(request);
                Iterator itr = items.iterator();

                while (itr.hasNext()) {
                    FileItem item = (FileItem)itr.next();
                    formFields.put(item.getFieldName(), item);
                }
            }
        }
        catch (FileUploadException ex) {
        }
        
        return formFields;
    }

    public static SessionData getSessionData(HttpServletRequest request) {

        if (request.getSession().getAttribute("sessionData") == null) {
            SessionData sessionData = new SessionData();
            request.getSession().setAttribute("sessionData", sessionData);
        }

        return (SessionData)request.getSession().getAttribute("sessionData");
    }
}
